package com.eco.fanliapp.admin.controller.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppUserRewardSetupMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.StringUtils;
import com.eco.fanliapp.vo.TbkOrderGetInfo;
import com.eco.fanliapp.vo.job.CountLauncherPay;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/web/order")
public class OrderManualController {

    @Autowired
    private IAppOrderDetailService iAppOrderDetailService;
    @Autowired
    private IGoodsFreeService iGoodsFreeService;
    @Autowired
    private IGoodsFreeService goodsFreeService;
    @Autowired
    private IAppUserService iAppUserService;

    @Autowired
    private IAppUserOrderService iAppUserOrderService;
    @Autowired
    private ICommissionFreezeService iCommissionFreezeService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;

    @Autowired
    private UpdateUserCommon updateUserCommon;


    @Autowired
    private IAppUserRedRewardService appUserRedRewardService;

    @Autowired
    private ISySwitchService iSySwitchService;

    @Autowired
    private IAppUserRewardSetupService iAppUserRewardSetupService;

    @Autowired
    private ITaobaoSchemeService taobaoSchemeService;

    @Autowired
    private ITaoBaoOrderService taobaoOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisTemplateService redisTemplateService;

    @Autowired
    private AppUserRewardSetupMapper appUserRewardSetupMapper;

    @Autowired
    private IAppUserRedRewardService IAppUserRedRewardService;

    @Autowired
    private IAppWxWithdrawalService iAppWxWithdrawalService;

    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;

    @Autowired
    private ITaoBaoOrderNewService taoBaoOrderNewService;

    private static final Logger log = LoggerFactory.getLogger(OrderManualController.class);

    /**
     * 处理订单手动置成结算
     * @param orderId
     * @param userId
     */
    @RequestMapping("/manualOrderNew")
    public ServerResponse manualOrderNew(String orderId,Long userId)throws Exception{
        //更新detail表
        AppOrderDetail appOrderDetail = iAppOrderDetailService.selectAppOrderDetailByTradeId(Long.valueOf(orderId));
        if(appOrderDetail == null){
            return ServerResponse.createBySuccessMessage("订单id关联不到用户");
        }
        appOrderDetail.setPayStatus("3");
        iAppOrderDetailService.updateById(appOrderDetail);

        //获取order表
        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.valueOf(orderId));
        if(CollectionUtils.isEmpty(userOrders)){
            return ServerResponse.createBySuccessMessage("order表未关联到用户");
        }

        if("3".equals(appOrderDetail.getPayStatus()) && 3 == userOrders.get(0).getOrderStatus()){
            return ServerResponse.createBySuccessMessage("订单已结算过，重复操作无效！");
        }
        for (AppUserOrder userOrder : userOrders) {
            //更新订单状态
            AppUserOrder appUserOrder = new AppUserOrder();
            appUserOrder.setTableId(userOrder.getTableId());
            appUserOrder.setOrderStatus(3);
            int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);

            if (i2 > 0) {
                //处理红包和任务
                handleRedOrTask(userOrder);
                //关联会员
                QueryWrapper<AppUser> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id",userId);
                AppUser appUser = iAppUserService.getOne(queryWrapper);

                //判断是否是免单库的商品
                if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
                    //处理免单商品结算
                    handleFreeGoods(userOrder, appOrderDetail, appUser);
                } else {
                    //处理非免单商品
                    handleNotFreeGoods(userOrder, appOrderDetail, appUser);
                }
                log.info("messagemessage结算订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
            } else {
                log.info("messagemessage结算订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
            }

        }
        return ServerResponse.createBySuccessMessage("操作成功");
    }

    /**
     * 处理红包和任务
     *
     * @param userOrder
     */
    public void handleRedOrTask(AppUserOrder userOrder) {
        //判断开关是否打开
        if (userOrder.getOrderGrade() == 1) {
            AppUserRewardSetup rewardSetup = null;
            if (redisTemplateService.hasKey("AppUserRewardSetup")) {
                rewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup", AppUserRewardSetup.class);
            } else {
                rewardSetup = appUserRewardSetupMapper.selectByPrimaryKey(1);
                redisTemplateService.set("AppUserRewardSetup", rewardSetup, 60 * 60);
            }
            //邀请赚钱红包（上级）
            AppUserRedReward appUserRedReward = new AppUserRedReward();
            long expireTime = DateFormatUtils.addDate(new Date(), rewardSetup.getInvitationRedMoneyExpireTime()).getTime();
            appUserRedReward.setExpireTime(expireTime);
            appUserRedReward.setOrderId(userOrder.getOrderId());
            appUserRedReward.setHbStatus(2);
            appUserRedReward.setHbType(2);
            int redMoneyInvi = IAppUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward);

            //首购红包（本级）
            AppUserRedReward appUserRedReward2 = new AppUserRedReward();
            long expireTime2 = DateFormatUtils.addDate(new Date(), rewardSetup.getTaskRedMoneyExpireTime()).getTime();
            appUserRedReward2.setExpireTime(expireTime2);
            appUserRedReward2.setOrderId(userOrder.getOrderId());
            appUserRedReward2.setHbType(3);
            appUserRedReward2.setHbStatus(2);
            int redMoneyTask = IAppUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward2);

            //增加或修改任务日志状态
            AppUserRedReward userRedReward = IAppUserRedRewardService.selectAppUserRedRewardById(userOrder.getOrderId(), userOrder.getUserId());
            if (userRedReward != null) {
                updateUserCommon.UpdateUserTaskStatus(userRedReward.getUserId(), 4);
            }
            log.info("订单结算更新红包状态订单号{}用户id{}邀请赚钱红包是否成功{}任务红包是否成功{}", userOrder.getOrderId(), userOrder.getUserId(), redMoneyInvi, redMoneyTask);
        }
    }

    /**
     * 结算免单商品
     *
     * @param userOrder
     * @param appOrderDetail
     */
    public void handleFreeGoods(AppUserOrder userOrder, AppOrderDetail appOrderDetail, AppUser appUser) throws Exception {
        //更新总返佣金
        iGoodsFreeService.updateTotalRetureAmountByGoodsId(userOrder.getTableId());

        //免单商品佣金延迟10天到账
        AppUserOrder userOrder4 = new AppUserOrder();//构建佣金延迟
        userOrder4.setLargeAmountYes(1);
        userOrder4.setLargeAmountTime(getDateTime(8));//延迟天数毫秒
        userOrder4.setTableId(userOrder.getTableId());
        userOrder4.setOrderSettleStatus(1);
        userOrder4.setOrderStatus(3);
        userOrder4.setFreezeDay(8);
        int i3 = iAppUserOrderService.updateAppUserOrder(userOrder4);
        log.info("结算订单(免单延迟)结果", i3);
        if (i3 > 0 && isSendMsg(7)) {
            iAppNewsLogService.newsType(userOrder.getUserId(),
                    NewsEnumLog.NEWS_FREE_BIGDELAY.getNewsType(),
                    BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
        }

        //结算成功公众号提醒
        log.info("app_order_detail的trade_id:{}", appOrderDetail.getTradeId());
        BigDecimal commission = userOrder.getCommission();
        String commissionStr = "0";
        if (commission != null) {
            commissionStr = userOrder.getCommission().toString();
        }
        commissionStr += "元";
        String tkEarningTime = appOrderDetail.getTkEarningTime();
        if (tkEarningTime == null) {
            tkEarningTime = "暂无";
        }
        ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser, "30006", appOrderDetail.getTradeId().toString(), commissionStr, tkEarningTime, appUser.getWechatNickname());

    }

    /**
     * 处理非免单商品结算
     *
     * @param userOrder
     * @param appOrderDetail
     */
    public void handleNotFreeGoods(AppUserOrder userOrder, AppOrderDetail appOrderDetail, AppUser appUser) throws IOException {
        //查询佣金是否符合佣金冻结设置
        CommissionFreeze freeze = null;
        if (redisTemplateService.hasKey("CommissionFreezeStuep")) {
            freeze = redisTemplateService.getTByKey("CommissionFreezeStuep", CommissionFreeze.class);
        } else {
            freeze = iCommissionFreezeService.selectByPrimaryKeyLIMIT(1);
            redisTemplateService.set("CommissionFreezeStuep", freeze, 60 * 60);
        }

        //相等返回0，大于返回1，小于返回-1
        AppUserOrder userOrder2 = new AppUserOrder();//构建佣金延迟
        BigDecimal userCommission = userOrder.getCommission();
        if (BigDecimalUtils.Format(userCommission).compareTo(BigDecimalUtils.Format(freeze.getCommissionlimit())) > 0) {
            userOrder2.setLargeAmountYes(1);
            userOrder2.setLargeAmountTime(getDateTime(freeze.getDelaydays()));//延迟天数毫秒
            userOrder2.setTableId(userOrder.getTableId());
            userOrder2.setOrderSettleStatus(1);
            userOrder2.setOrderStatus(3);
            userOrder2.setFreezeDay(freeze.getDelaydays());
            int i3 = iAppUserOrderService.updateAppUserOrder(userOrder2);
            if (i3 > 0 && isSendMsg(7)) {
                iAppNewsLogService.newsType(appUser.getUserId(), NewsEnumLog.NEWS_BIGDELAY.getNewsType(),
                        BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
            }
        } else {
            BigDecimal beforeBalance = appUser.getBalance();
            //根据订单id查询订单
            switch (userOrder.getOrderGrade()) {
                case 1:
                    int i3 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(), BigDecimalUtils.Format(userOrder.getCommission()));
                    log.info("message{}自己{}", userOrder.getUserId(), userOrder.getCommission());
                    if (i3 > 0) {
                        //新增用户余额变动日志记录
                        syUserMoneyLogService.addSyUserMoneyLog(userOrder.getUserId(), beforeBalance, BigDecimalUtils.Format(userOrder.getCommission()), "普通商品补贴到账", 2, 0);
                        if (isSendMsg(7)) {
                            iAppNewsLogService.newsType(userOrder.getUserId(), NewsEnumLog.NEWS_ORDER_SETTLE.getNewsType(),
                                    BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                        }
                        //结算成功公众号提醒
                        BigDecimal commission = userOrder.getCommission();
                        String commissionStr = "0";
                        if (commission != null) {
                            commissionStr = userOrder.getCommission().toString();
                        }
                        commissionStr += "元";
                        String tkEarningTime = appOrderDetail.getTkEarningTime();
                        if (tkEarningTime == null) {
                            tkEarningTime = "暂无";
                        }
                        ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser, "30006", appOrderDetail.getTradeId().toString(), commissionStr, tkEarningTime, appUser.getWechatNickname());
                        log.info("公众号发消1息返回结果{}", JSONObject.toJSONString(result));
                    }
                    break;
                case 2:
                    int i4 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(), BigDecimalUtils.Format(userOrder.getCommission()));
                    log.info("message{}2级{}", userOrder.getUserId(), userOrder.getCommission());
                    log.info("普通商品补贴到账开始发送消息{}", i4);
                    if (i4 > 0) {
                        //新增用户余额变动日志记录
                        syUserMoneyLogService.addSyUserMoneyLog(userOrder.getUserId(), beforeBalance, BigDecimalUtils.Format(userOrder.getCommission()), "普通商品2级补贴到账", 2, 0);
                        if (isSendMsg(7)) {
                            iAppNewsLogService.newsType(userOrder.getUserId(), NewsEnumLog.NEWS_ORDER_SUPER_SETTLE.getNewsType(),
                                    BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                        }
                        break;
                    }
                default:
                    break;
            }
            AppUserOrder userOrder3 = new AppUserOrder();//构建佣金延迟
            userOrder3.setOrderStatus(3);
            userOrder3.setOrderSettleStatus(2);
            userOrder3.setTableId(userOrder.getTableId());
            int i4 = iAppUserOrderService.updateAppUserOrder(userOrder3);
            log.info("结算订单（普通商品不延迟）已经将钱转到账i4{}", i4);
        }
    }

    /**设置红包到期日期为当前
     * @return
     */
    @RequestMapping("/manualRedMoneyNow")
    public ServerResponse<String> manualRedMoneyNow(String orderId){
        QueryWrapper<AppUserRedReward> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);

        List<AppUserRedReward> appUserRedRewards = appUserRedRewardService.list(queryWrapper);
        for (AppUserRedReward appUserRedReward : appUserRedRewards) {
            if (appUserRedReward.getHbType() == 2) {
                AppUserRedReward appUserRedRewardNew = new AppUserRedReward();
                appUserRedRewardNew.setTableId(appUserRedReward.getTableId());
                appUserRedRewardNew.setExpireTime(System.currentTimeMillis() - 1000 * 30);
                appUserRedRewardService.updateById(appUserRedRewardNew);
            }
            if (appUserRedReward.getHbType() == 3) {
                AppUserRedReward appUserRedRewardNew = new AppUserRedReward();
                appUserRedRewardNew.setTableId(appUserRedReward.getTableId());
                appUserRedRewardNew.setInvalidTime(System.currentTimeMillis() - 1000 * 30);
                appUserRedRewardService.updateById(appUserRedRewardNew);
            }

        }

/*
        try {
            long time = new Date().getTime();
            int i = appUserRedRewardService.updateNewRedMoneyStatusSx(time);
            log.info("更新失效任务红包定时任务执行结果{}",i);
            appUserRedRewardService.updateHbStatusTask();
            log.info("更新任务红包领取定时任务执行结果{}");
        } catch (Exception e) {
            e.printStackTrace();
//            log.info("更新任务红包领取定时任务执行结果{}");
        }finally {
        }
        try {
            long time = new Date().getTime();
            int i = appUserRedRewardService.updateRedMoneyStatusSx(time);
            log.info("更新失效新人红包定时任务执行结果{}",i);
            int j = appUserRedRewardService.updateRedMoneyStatusLq(time);
            log.info("更新可以领取的邀请赚钱红包定时任务执行结果{}",j);
        } catch (Exception e) {

        }finally {
        }
*/


//        appUserRedRewardService.updateAppUserRedReward(orderId,);

        //付款订单定时任务
//        orderDetailTaskService.orderPayTask(false);
//        orderDetailTaskService.orderTask4();
        return ServerResponse.createBySuccess();
    }

    /**
     * TODO 获取当前时间的20分钟前，用来订单查询
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getSystemTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -20);//获取20分钟前的时间
        Date beforeD = beforeTime.getTime();
        return df.format(beforeD);
    }
    /**
     * TODO 获取当前时间的2小时前，用来订单查询
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getTwoHourSystemTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -120);//获取2小时前的时间
        Date beforeD = beforeTime.getTime();
        return df.format(beforeD);
    }
    /**
     * TODO 获取当前时间的20分钟前，用来订单查询
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getNowTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(new Date());
    }
    /**
     * 手动的调用一次付款订单拉取定时任务
     * @return
     */
    @RequestMapping("/manualPayOrder")
    public ServerResponse<String> manualPayOrder(String startTime,String endTime,Long tkStatus,Long orderCountType,String orderQueryType){

        //开始时间、结束时间
        if(StringUtils.isNull(startTime)){
            startTime = getTwoHourSystemTime();//.replace(" ", "%20");
        }
        if(StringUtils.isNull(endTime)){
            endTime = getNowTime();
        }
        //淘客订单状态，12-付款，13-关闭，14-确认收货，3-结算成功;不传，表示所有状态
        if(tkStatus == null){
            tkStatus = 12L;
        }
        //member_type   推广者角色类型,2:二方，3:三方，不传，表示所有角色
        if(orderCountType ==null){
            orderCountType = 2L;
        }
        if(StringUtils.isNull(orderQueryType)){
            orderQueryType = "2";//查询时间类型，1：按照订单淘客创建时间查询，2:按照订单淘客付款时间查询，3:按照订单淘客结算时间查询

        }
        //,Long orderScene
//        if(orderScene == null){
//            orderScene = 2L;//场景订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1
//
//        }

        //获取所有的联盟信息
        List<TaobaoScheme> taobaoSchemes = taobaoSchemeService.selectDistinctTaobaoSchemeList(null);
        int type = 1;
        //当前时间
        long startMillions = System.currentTimeMillis();
        try {

            if (taobaoSchemes.size() > 0) {

                for (long orderScene = 1; orderScene <= 3; orderScene++) {
                    CountLauncherPay countLauncherPay  = new CountLauncherPay(taobaoSchemes.size());
                    taoBaoOrderNewService.setCountLauncherPay(countLauncherPay);

                    Long pageNo = 1L;
                    for (TaobaoScheme taobaoScheme2 : taobaoSchemes) {
                        String appSession = taobaoScheme2.getAppSession();
//                        String appSession = "61029209f230ea817a2525700af91dd05727345145e81fd3322183257";
                        //付款
                        if(tkStatus == 12){
                            taoBaoOrderNewService.getPayOrderDetail(appSession,
                                    startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, type,null);
                        }
                        //结算
                        if(tkStatus == 3){
                            taoBaoOrderNewService.getSettleOrderDetail(appSession,
                                    startTime, endTime, pageNo, tkStatus,orderCountType, orderQueryType, orderScene, type, null);
                        }
                        //完成
                        if(tkStatus == 14){
                            taoBaoOrderNewService.getSuccOrderDetail(appSession,
                                    startTime, endTime, pageNo,tkStatus, orderCountType, orderQueryType, orderScene, type, null);
                        }
                        //失效
                        if(tkStatus == 13){
                            taoBaoOrderNewService.getFailOrderDetail(appSession,
                                    startTime, endTime, pageNo, tkStatus,orderCountType, orderQueryType,orderScene, type,null);
                        }
                    }

                    try {
                        Thread.sleep(500 * (type + 1));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    while (countLauncherPay.getCount() > 0) {
                        if ((System.currentTimeMillis() - startMillions) > 1000 * 60 * 2) {
                            break;
                        }
                        log.info("*********等待异步方法执行完毕-付款订单定时任务" + "--countLauncherPay=" + countLauncherPay.getCount() + "--time=" + System.currentTimeMillis());
                        try {
                            Thread.sleep(2000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("*********一次拉取付款订单错误" + "--startTime=" + startTime + "--endTime=" + endTime);
        } finally {
            log.info("*********结束一次拉取付款订单" + "--startTime=" + startTime + "--endTime=" + endTime);
        }
        return ServerResponse.createBySuccess();
    }


    /**
     * 手动的调用一次失效订单拉取定时任务
     * @param userId
     * @return
     */
    @RequestMapping("/manualFailOrder")
    public ServerResponse<String> manualFailOrder(String userId,String orderId){

        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000 * 2;

        try {
            AppOrderDetail appOrderDetail = iAppOrderDetailService.selectAppOrderDetailByTradeId(Long.parseLong(orderId));

            int i = 0;
            TbkOrderGetInfo.NTbkOrderDataBean order = new TbkOrderGetInfo.NTbkOrderDataBean();
            order.setTradeId(Long.parseLong(orderId));
            //免单处理
            AppOrderDetail appOrderDetail1 = iAppOrderDetailService.selectAppOrderDetailByTradeId(order.getTradeId());

            order.setNumIid(appOrderDetail1.getItemId());
            order.setPubSharePreFee(appOrderDetail1.getPubSharePreFee());

            if (appOrderDetail1 != null && appOrderDetail1.getTradeId() != null) {
                appOrderDetail.setPubSharePreFee("0");
                appOrderDetail.setFanliMoney(BigDecimal.valueOf(0));
                appOrderDetail.setGoodFrees(appOrderDetail1.getGoodFrees());
                appOrderDetail.setItemPic(appOrderDetail1.getItemPic());
                appOrderDetail.setFanliMoney(appOrderDetail1.getFanliMoney());
                i = 1;
            }



            if (appOrderDetail1 ==null ||
                    (appOrderDetail1 != null && appOrderDetail1.getTradeId() != null && appOrderDetail1.getTkStatus() != null && appOrderDetail1.getTkStatus() != 13)) {
                i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                log.info("失效订单{}入库成功", orderId);
                if (i > 0) {
                    if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {

                        //查询是否是免单库的商品如果是就失效订单数加1
                        GoodsFree goods = iGoodsFreeService.selectByGoodsId(order.getNumIid());
                        if (goods != null) {
                            log.info("获取到免单商品{}", goods.getGoodsId());
                            iGoodsFreeService.updateInvalidOrdersByGoodsId(goods.getId());
                        }
                    }
                }
            }

            if (i > 0) {

                List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(order.getTradeId());
                AppUserOrder appUserOrder = new AppUserOrder();
                for (AppUserOrder userOrder : userOrders) {
                    if (userOrder != null && userOrder.getOrderId() != null && userOrder.getOrderStatus() == 13) {
                        log.info("message失效订单{}处理过了用户为{}", userOrder.getOrderId(), userOrder.getUserId());
                    } else {
                        appUserOrder.setTableId(userOrder.getTableId());
                        appUserOrder.setOrderStatus(13);
                        appUserOrder.setCommission(BigDecimal.valueOf(0));
                        int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
                        if (i2 > 0) {
                            //查询失效订单是否有红包有红包就把红包设置成失效4
                            int appRedMoney = appUserRedRewardService.updateAppUserRedReward(userOrder.getOrderId(), 4);
                            AppUserRedReward appUserRedReward = appUserRedRewardService.selectAppUserRedRewardById(userOrder.getOrderId(),userOrder.getUserId());
                            if(appUserRedReward != null){
                                updateUserCommon.UpdateUserTaskStatus(appUserRedReward.getUserId(),6);
                            }

                            log.info("设置订单失效是否{}成功订单id{}用户id{}", appRedMoney, userOrder.getOrderId(), userOrder.getUserId());
                            switch (userOrder.getOrderGrade()) {
                                case 1:
                                    iAppNewsLogService.newsType(userOrder.getUserId(),
                                            NewsEnumLog.NEWS_ORDER_FAIL.getNewsType(),
                                            BigDecimalUtils.Format(userOrder.getCommission()),"淘宝网", appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                                    break;
                                case 2:
                                    iAppNewsLogService.newsType(userOrder.getUserId(),
                                            NewsEnumLog.NEWS_ORDER_SUPER_FAIL.getNewsType(),
                                            BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                                    break;
							/*	case 3:
									iAppNewsLogService.newsType(userOrder.getUserId(),
											NewsEnumLog.NEWS_ORDER_LEVEL_FAIL.getNewsType(),
											BigDecimalUtils.Format(userOrder.getCommission()),userOrder.getCommission().toString());
									break;*/
                                default:
                                    break;
                            }
                            log.info("messagemessage失效订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                        } else {
                            log.info("messagemessage失效订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                        }
                    }
                }
            } else {
                log.error("失效订单{}入库失败{}", order.getTradeId(), new Throwable().getStackTrace());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return ServerResponse.createBySuccess();
    }



//    @RequestMapping("/manualOrder")
    public void manualOrder(String orderId,Long userId){

        AppUserOrder appUserOrder = new AppUserOrder();
        AppUserOrder userOrder2 = new AppUserOrder();//构建佣金延迟

        TbkOrderGetInfo.NTbkOrderDataBean order = new TbkOrderGetInfo.NTbkOrderDataBean();
        order.setTradeId(Long.parseLong(orderId));
        //免单处理
        AppOrderDetail appOrderDetail1 = iAppOrderDetailService.selectAppOrderDetailByTradeId(order.getTradeId());

        order.setNumIid(appOrderDetail1.getItemId());
        order.setPubSharePreFee(appOrderDetail1.getPubSharePreFee());


        AppUser appUser = iAppUserService.selectAppUserByUserId(userId);

        if (appOrderDetail1 == null || appOrderDetail1.getTradeId() == null) {
            GoodsFree goodsFree = iGoodsFreeService.selectByGoodsId(order.getNumIid());
            ServerResponse<String> serverResponse = goodsFreeService.checkHaveBuy(appUser == null ? 0 : appUser.getUserId(), 1);
            int status = serverResponse.getStatus();
            //如果是用户首单并且免单商品，记录免单状态
            if (goodsFree != null && status == 515 && appUser != null && goodsFree.getNumber() > 0) {

                appOrderDetail1.setGoodFrees(new Long(1));
            }
        } else {
            appOrderDetail1.setGoodFrees(appOrderDetail1.getGoodFrees());
            appOrderDetail1.setItemPic(appOrderDetail1.getItemPic());
            appOrderDetail1.setFanliMoney(appOrderDetail1.getFanliMoney());
        }
        appOrderDetail1.setTkStatus(3);
        appOrderDetail1.setPayStatus("3");
        int i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail1);
        if (i > 0) {
            log.info("结算订单{}入库成功", order.getTradeId());
            List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(order.getTradeId());
            for (AppUserOrder userOrder : userOrders) {
                if (userOrder != null && userOrder.getOrderId() != null && (userOrder.getOrderStatus() == 3 || userOrder.getOrderStatus() == 13)) {
                    log.info("message结算订单处理{}过了用户为{}", userOrder.getOrderId(), userOrder.getUserId());
                } else {
                    appUserOrder.setTableId(userOrder.getTableId());
                    appUserOrder.setOrderStatus(3);
                    int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
                    if (i2 > 0) {
                        AppUserRewardSetup rewardSetup = null;
                        if (redisTemplate.hasKey("AppUserRewardSetup")) {
                            rewardSetup = (AppUserRewardSetup) redisTemplate.opsForValue().get("AppUserRewardSetup");
                        } else {
                            rewardSetup = iAppUserRewardSetupService.getById(1);
                            redisTemplate.opsForValue().set("AppUserRewardSetup", rewardSetup, 1, TimeUnit.HOURS);
                        }
                        //订单结算成功修改红包状态为2
                        //设置任务红包和邀请赚钱红包的已收货到账时间
                        if (userOrder.getOrderGrade() == 1) {
                            //邀请赚钱红包
                            AppUserRedReward appUserRedReward = new AppUserRedReward();
                            long expireTime = DateFormatUtils.addDate(new Date(), rewardSetup.getInvitationRedMoneyExpireTime()).getTime();
                            appUserRedReward.setExpireTime(expireTime);
                            appUserRedReward.setOrderId(userOrder.getOrderId());
                            appUserRedReward.setHbType(2);
                            appUserRedReward.setHbStatus(2);
                            int redMoneyInvi = appUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward);

                            //任务红包
                            AppUserRedReward appUserRedReward2 = new AppUserRedReward();
                            long expireTime2 = DateFormatUtils.addDate(new Date(), rewardSetup.getTaskRedMoneyExpireTime()).getTime();
                            appUserRedReward2.setExpireTime(expireTime2);
                            appUserRedReward2.setOrderId(userOrder.getOrderId());
                            appUserRedReward2.setHbType(3);
                            appUserRedReward2.setHbStatus(2);
                            int redMoneyTask = appUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward2);


//                                    int readMoney = IAppUserRedRewardService.updateAppUserRedReward(userOrder.getOrderId(),2);
                            log.info("订单结算更新红包状态订单号{}用户id{}邀请赚钱红包是否成功{}任务红包是否成功{}", userOrder.getOrderId(), userOrder.getUserId(), redMoneyInvi, redMoneyTask);
                        }
                        //查询佣金是否符合佣金冻结设置
                        CommissionFreeze freeze = null;
                        if (redisTemplate.hasKey("CommissionFreezeStuep")) {
                            freeze = (CommissionFreeze) redisTemplate.opsForValue().get("CommissionFreezeStuep");
                        } else {
                            freeze = iCommissionFreezeService.selectByPrimaryKeyLIMIT(1);
                            redisTemplate.opsForValue().set("CommissionFreezeStuep", freeze, 1, TimeUnit.HOURS);
                        }
                        //相等返回0，大于返回1，小于返回-1
                        if (BigDecimalUtils.Format(order.getPubSharePreFee()).compareTo(
                                BigDecimalUtils.Format(freeze.getCommissionlimit())) > 0) {
                            userOrder2.setLargeAmountYes(1);
                            userOrder2.setLargeAmountTime(getDateTime(freeze.getDelaydays()));//延迟天数毫秒
                            userOrder2.setTableId(userOrder.getTableId());
                            userOrder2.setOrderSettleStatus(1);
                            int i3 = iAppUserOrderService.updateAppUserOrder(userOrder2);
//									if(i3 > 0) {
//										iAppNewsLogService.newsType(appUser.getUserId(),
//												NewsEnumLog.NEWS_BIGDELAY.getNewsType(),
//												BigDecimalUtils.Format(userOrder.getCommission()));
//									}
                        } else {
                            //查询是否是免单库的商品
                            GoodsFree goods = iGoodsFreeService.selectByGoodsId(order.getNumIid());
                            if (goods != null && appOrderDetail1.getGoodFrees() != null && appOrderDetail1.getGoodFrees() == 1) {

                                int i6 = iAppUserService.updateAppUseraddbalance(appUser.getUserId(),
                                        BigDecimalUtils.Format(userOrder.getCommission()));
                                if (i6 > 0) {
                                    iAppNewsLogService.newsType(appUser.getUserId(),
                                            NewsEnumLog.NEWS_ORDER_SETTLE.getNewsType(),
                                            BigDecimalUtils.Format(userOrder.getCommission()), goods.getGoodsName(), userOrder.getCommission().toString());
                                }
                                //计算总佣金
                                iGoodsFreeService.updateTotalRetureAmountByGoodsId(goods.getId());

                            } else {
                                //根据订单id查询订单
                                     /*   AppUserOrder appUserOrder1 = iAppUserOrderService.selectAppUserOrderById(userOrder.getTableId());
                                        if(appUserOrder1.getOrderStatus() != 3) {*/
                                switch (userOrder.getOrderGrade()) {
                                    case 1:
                                        int i3 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(),
                                                BigDecimalUtils.Format(userOrder.getCommission()));
                                        log.info("message{}自己{}", userOrder.getUserId(), userOrder.getCommission());
                                        if (i3 > 0) {
                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                    NewsEnumLog.NEWS_ORDER_SETTLE.getNewsType(),
                                                    BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail1.getItemTitle(), userOrder.getCommission().toString());
                                        }
                                        break;
                                    case 2:
                                        int i4 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(),
                                                BigDecimalUtils.Format(userOrder.getCommission()));
                                        log.info("message{}2级{}", userOrder.getUserId(), userOrder.getCommission());
                                        if (i4 > 0) {
                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                    NewsEnumLog.NEWS_ORDER_SUPER_SETTLE.getNewsType(),
                                                    BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                                        }
                                        break;
                                    default:
                                        break;
//                                            }
                                }
                            }

                            AppUserOrder userOrder3 = new AppUserOrder();//构建佣金延迟
                            userOrder3.setOrderStatus(3);
                            userOrder3.setOrderSettleStatus(2);
                            userOrder3.setTableId(userOrder.getTableId());
                            int i4 = iAppUserOrderService.updateAppUserOrder(userOrder3);
                            log.info("结算订单已经将钱转到账i4{}", i4);
                        }//佣金冻结结束
                        log.info("messagemessage结算订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                    } else {
                        log.info("messagemessage结算订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                    }
                }
            }
        } else {
            log.error("结算订单{}入库失败{}", order.getTradeId(), new Throwable().getStackTrace());
        }
    }
    /**
     * 获取指定时间的时间戳
     * 一天是86400000
     *
     * @param start 天数
     * @return
     */
    public static long getDateTime(Integer start) {

        return DateUtils.addDays(new Date(), start).getTime();
    }

    @GetMapping("manualOrder")
    public String manualOrder(Long userId,Long orderId) throws InterruptedException {
        AppUserOrder appUserOrder = new AppUserOrder();
        AppUserOrder userOrder2 = new AppUserOrder();//构建佣金延迟
        if(userId ==null || orderId == null) {
            return "参数错误";
        }

        AppUser user = iAppUserService.selectAppUserByUserId(userId);
        if(user == null){
            return "用户不存在";
        }
        AppOrderDetail appOrderDetail1 = iAppOrderDetailService.selectAppOrderDetailByTradeId(orderId);

        if (appOrderDetail1 == null || appOrderDetail1.getTradeId() == null) {
            return "订单不存在";

           /* GoodsFree goodsFree = iGoodsFreeService.selectByGoodsId(appOrderDetail1.getItemId());
            ServerResponse<String> serverResponse = goodsFreeService.checkHaveBuy(userId, 1);
            int status = serverResponse.getStatus();
            //如果是用户首单并且免单商品，记录免单状态
            if (goodsFree != null && status == 515 && userId != null && goodsFree.getNumber() > 0) {

                appOrderDetail1.setGoodFrees(new Long(1));
            }*/
        } else {


            appOrderDetail1.setPayStatus("3");
            appOrderDetail1.setTkStatus(3);
            appOrderDetail1.setTableUpdateTime(System.currentTimeMillis());
        }
        if(appOrderDetail1.getTaobaoUserId().longValue() !=user.getTaobaoUserId().longValue()){
            return "用户订单不匹配";
        }
        int i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail1);
        if (i > 0) {
            log.info("结算订单{}入库成功", orderId);

            List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(orderId);
            BigDecimal userCommission = new BigDecimal("0");
            if(!CollectionUtils.isEmpty(userOrders)) {
                userCommission = userOrders.get(0).getCommission();
            }
            for (AppUserOrder userOrder : userOrders) {
                if (userOrder != null && userOrder.getOrderId() != null && (userOrder.getOrderStatus() == 3 || userOrder.getOrderStatus() == 13)) {
                    log.info("message结算订单处理{}过了用户为{}", userOrder.getOrderId(), userOrder.getUserId());
                    return "结算订单处理过了";
                } else {
                    appUserOrder.setTableId(userOrder.getTableId());
                    appUserOrder.setOrderStatus(3);
                    int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
                    if (i2 > 0) {
                        //订单结算成功修改红包状态为2
                        //设置任务红包和邀请赚钱红包的已收货到账时间
                        if (userOrder.getOrderGrade() == 1) {
                            AppUserRewardSetup rewardSetup = null;
                            if (redisTemplateService.hasKey("AppUserRewardSetup")) {
                                rewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup",AppUserRewardSetup.class);
                            } else {
                                rewardSetup = iAppUserRewardSetupService.getById(1);
                                redisTemplateService.set("AppUserRewardSetup", rewardSetup, 60*60);
                            }
                            //邀请赚钱红包
                            AppUserRedReward appUserRedReward = new AppUserRedReward();
                            long expireTime = DateFormatUtils.addDate(new Date(), rewardSetup.getInvitationRedMoneyExpireTime()).getTime();
                            appUserRedReward.setExpireTime(expireTime);
                            appUserRedReward.setOrderId(userOrder.getOrderId());
                            appUserRedReward.setHbType(2);
                            appUserRedReward.setHbStatus(2);
                            int redMoneyInvi = appUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward);

                            //任务红包
                            AppUserRedReward appUserRedReward2 = new AppUserRedReward();
                            long expireTime2 = DateFormatUtils.addDate(new Date(), rewardSetup.getTaskRedMoneyExpireTime()).getTime();
                            appUserRedReward2.setExpireTime(expireTime2);
                            appUserRedReward2.setOrderId(userOrder.getOrderId());
                            appUserRedReward2.setHbType(3);
                            appUserRedReward2.setHbStatus(2);
                            int redMoneyTask = appUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward2);
                            //增加或修改任务日志状态
                            AppUserRedReward userRedReward = appUserRedRewardService.selectAppUserRedRewardById(userOrder.getOrderId(),userOrder.getUserId());
                            if(userRedReward != null){
                                log.info("订单结算---更新日志状态红包userI{}",userRedReward.getUserId());
                                updateUserCommon.UpdateUserTaskStatus(userRedReward.getUserId(),4);
                            }
//                                      int readMoney = IAppUserRedRewardService.updateAppUserRedReward(userOrder.getOrderId(),2);
                            log.info("订单结算更新红包状态订单号{}用户id{}邀请赚钱红包是否成功{}任务红包是否成功{}", userOrder.getOrderId(), userOrder.getUserId(), redMoneyInvi, redMoneyTask);
                        }


                        //查询是否是免单库的商品
                        //GoodsFree goods = iGoodsFreeService.selectByGoodsId(appOrderDetail1.getItemId());
                        if (appOrderDetail1.getGoodFrees() != null && appOrderDetail1.getGoodFrees() == 1) {
                            //计算总佣金
                            iGoodsFreeService.updateTotalRetureAmountByGoodsId(appOrderDetail1.getItemId().intValue());
                            AppUserOrder userOrder4 = new AppUserOrder();//构建佣金延迟
                            userOrder4.setLargeAmountYes(1);
                            userOrder4.setLargeAmountTime(getDateTime(10));//延迟天数毫秒
                            userOrder4.setTableId(userOrder.getTableId());
                            userOrder4.setOrderSettleStatus(1);
                            int i3 = iAppUserOrderService.updateAppUserOrder(userOrder4);
                            log.info("结算订单(免单延迟)结果", i3);
//                                            int i6 = iAppUserService.updateAppUseraddbalance(appUser.getUserId(),
//                                                    BigDecimalUtils.Format(userOrder.getCommission()));
                            if (i3 > 0 && isSendMsg(7)) {
                                iAppNewsLogService.newsType(userOrder.getUserId(),
                                        NewsEnumLog.NEWS_FREE_BIGDELAY.getNewsType(),
                                        BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail1.getItemTitle(), userOrder.getCommission().toString());
                            }
                            // TODO: 结算成功公众号提醒
                            //this.weCheatMessage(appUser, "3003", BigDecimalUtils.Format(userOrder.getCommission()).toString());
                        } else {
                            //查询佣金是否符合佣金冻结设置

                            CommissionFreeze freeze = null;
                            if (redisTemplate.hasKey("CommissionFreezeStuep")) {
                                freeze = (CommissionFreeze) redisTemplate.opsForValue().get("CommissionFreezeStuep");
                            } else {
                                freeze = iCommissionFreezeService.selectByPrimaryKeyLIMIT(1);
                                redisTemplate.opsForValue().set("CommissionFreezeStuep", freeze, 1, TimeUnit.HOURS);
                            }
                            //相等返回0，大于返回1，小于返回-1
                            if (BigDecimalUtils.Format(userCommission).compareTo(
                                    BigDecimalUtils.Format(freeze.getCommissionlimit())) > 0) {
                                userOrder2.setLargeAmountYes(1);
                                userOrder2.setLargeAmountTime(getDateTime(freeze.getDelaydays()));//延迟天数毫秒
                                userOrder2.setTableId(userOrder.getTableId());
                                userOrder2.setOrderSettleStatus(1);
                                int i3 = iAppUserOrderService.updateAppUserOrder(userOrder2);
                                log.info("结算订单(普通商品延迟){}", i3);
                                if (i3 > 0 && isSendMsg(7)) {
                                    iAppNewsLogService.newsType(userOrder.getUserId(),
                                            NewsEnumLog.NEWS_BIGDELAY.getNewsType(),
                                            BigDecimalUtils.Format(userOrder.getCommission()),appOrderDetail1.getItemTitle(), userOrder.getCommission().toString());
                                }
                            } else {
                                //根据订单id查询订单
                                         /* AppUserOrder appUserOrder1 = iAppUserOrderService.selectAppUserOrderById(userOrder.getTableId());
                                        if(appUserOrder1.getOrderStatus() != 3) {*/
                                switch (userOrder.getOrderGrade()) {
                                    case 1:
                                        int i3 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(),
                                                BigDecimalUtils.Format(userOrder.getCommission()));
                                        log.info("message{}自己{}", userOrder.getUserId(), userOrder.getCommission());
                                        log.info("普通商品补贴到账开始发送消息{}",i3);
                                        if (i3 > 0 ) {
                                            if(isSendMsg(7)){
                                                iAppNewsLogService.newsType(userOrder.getUserId(),
                                                        NewsEnumLog.NEWS_ORDER_SETTLE.getNewsType(),
                                                        BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail1.getItemTitle(), userOrder.getCommission().toString());
                                            }
                                           /* if(isSendMsg(8)){
                                                iAppNewsLogService.newsType(userOrder.getUserId(),
                                                        NewsEnumLog.NEWS_ORDER_SUBSIDY.getNewsType(),
                                                        BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail1.getItemTitle(), userOrder.getCommission().toString());
                                            }*/
                                            // TODO: 结算成功公众号提醒
                                            //this.weCheatMessage(appUser, "3003", BigDecimalUtils.Format(userOrder.getCommission()).toString());
                                        }
                                        break;
                                    case 2:
                                        int i4 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(),
                                                BigDecimalUtils.Format(userOrder.getCommission()));
                                        log.info("message{}2级{}", userOrder.getUserId(), userOrder.getCommission());
                                        log.info("普通商品补贴到账开始发送消息{}",i4);
                                        if (i4 > 0 ) {
                                            if(isSendMsg(7)){
                                                iAppNewsLogService.newsType(userOrder.getUserId(),
                                                        NewsEnumLog.NEWS_ORDER_SUPER_SETTLE.getNewsType(),
                                                        BigDecimalUtils.Format(userOrder.getCommission()),userOrder.getCommission().toString());
                                            }
                                           /* if(isSendMsg(8)) {
                                                iAppNewsLogService.newsType(userOrder.getUserId(),
                                                        NewsEnumLog.NEWS_ORDER_SUBSIDY.getNewsType(),
                                                        BigDecimalUtils.Format(userOrder.getCommission()), appOrderDetail1.getItemTitle(),userOrder.getCommission().toString());
                                            }*/
                                            // TODO: 好友结算成功公众号提醒
                                            //this.weCheatMessage(appUser, "3004", BigDecimalUtils.Format(userOrder.getCommission()).toString());
                                        }
                                        break;
                                               /* case 3:
                                                    int i5 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(),
                                                            BigDecimalUtils.Format(userOrder.getCommission()));
                                                    log.info("message{}3级{}", userOrder.getUserId(), userOrder.getCommission());
                                                    if (i5 > 0) {
                                                        iAppNewsLogService.newsType(userOrder.getUserId(),
                                                                NewsEnumLog.NEWS_ORDER_LEVEL_SETTLE.getNewsType(),
                                                                BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                                                    }
                                                    break;*/
                                    default:
                                        break;
//                                            }
                                }
                                AppUserOrder userOrder3 = new AppUserOrder();//构建佣金延迟
                                userOrder3.setOrderSettleStatus(2);
                                userOrder3.setTableId(userOrder.getTableId());
                                int i4 = iAppUserOrderService.updateAppUserOrder(userOrder3);
                                log.info("结算订单（普通商品不延迟）已经将钱转到账i4{}", i4);
                            }
                        }
                        log.info("messagemessage结算订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                    } else {
                        log.info("messagemessage结算订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                        return "结算订单处理失败";
                    }
                }
            }
        } else {
            log.error("结算订单{}入库失败{}", orderId, new Throwable().getStackTrace());
            return "结算订单入库失败";
        }
        Thread.sleep(1000L);


        return "成功";
    }

    @GetMapping("updateDate")
    public  String test1(Long userId,Integer moneyType){
        AppUserRedReward appUserRedReward = new AppUserRedReward();
        appUserRedReward.setUserId(userId);
       // appUserRedReward

        return "";
        }

    @GetMapping("abc")
    public  String abc(Long userId,Integer moneyType){
        iAppNewsLogService.newsType(600953646496L,NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),new BigDecimal("2.80"),"测试商品","7.8");
        return "";
    }
    /**
     * 通过开关判断是否要发消息
     * @id 开关类型
     * @return
     */
    private Boolean isSendMsg(int id) {
        //查询开关表是否发消息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("table_id", id);
        SySwitch sySwitch = iSySwitchService.getOne(queryWrapper);
        if (sySwitch == null) return false;
        if (sySwitch.getState() == 1) {
            log.info("消息类型{} 消息开发送消息",id);
            return true;
        }
        log.info("消息类型{} 消息关",id);
        return false;
    }

}
